package com.hxx.widget.sheet

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import com.hxx.widget.R

/**
 * 底部选项列表子项
 */
class BottomSheetListItem @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    init {
        LayoutInflater.from(context)
            .inflate(R.layout.widget_layout_bottom_sheet_list_item, this, true).apply {
                val a =
                    context.obtainStyledAttributes(attrs, R.styleable.widget_BottomSheetListItem)
                val title =
                    a.getString(R.styleable.widget_BottomSheetListItem_widget_sheet_item_title)
                val icon =
                    a.getResourceId(
                        R.styleable.widget_BottomSheetListItem_widget_sheet_item_icon,
                        R.drawable.widget_ic_plus
                    )
                findViewById<AppCompatTextView>(R.id.widget_sheet_item_title).text = title
                findViewById<AppCompatImageView>(R.id.widget_sheet_item_icon).setImageResource(icon)
                a.recycle()
            }
    }

    fun setTitleIcon(title: String, icon: Int) {
        findViewById<AppCompatTextView>(R.id.widget_sheet_item_title).text = title
        findViewById<AppCompatImageView>(R.id.widget_sheet_item_icon).setImageResource(icon)
    }

    /**
     * 替换占位view
     */
    fun replaceChildView(targetView: View) {
        val placeholder = findViewById<View>(R.id.placeHolderView)
        (placeholder.parent as ViewGroup).apply {
            removeView(placeholder)
            val lp = placeholder.layoutParams
            targetView.id = placeholder.id
            targetView.layoutParams = lp
            addView(targetView)
            targetView.visibility = View.VISIBLE
        }
    }
}